//
//  CZRefreshView.swift
//  项目框架
//
//  Created by yang on 16/3/4.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SnapKit


/*
1.视图界面分析
2.功能分析
*/

/*
界面分析
1.3个组件 -- 提示label, 提示下拉的图片, 加载的图片
2.加在哪里? -- 加TableView
*/
/*
功能分析
1. 如何确定我的下拉刷新的状态
1.1 loading状态如何确定

2. 相应状态对应的视图变化
1.1 在哪里去实现视图的改变

*/

//分析状态
enum RefreshType:Int{
    //正常
    case Normal = 0
    //拖拽
    case Pulling = 1
    //加载
    case Loading = 2
    

}
class CZRefreshView: UIControl {

    //成员变量
    var scrollView:UIScrollView?
    //记录一下过去的状态
    var oldStatus:RefreshType = .Normal
    
    //定义一个属性来记录状态，默认为正常
    var status:RefreshType = .Normal{
    
        didSet{
        
            switch status{
            
            case .Normal:print("正常状态")
                //文字状态
                messageLabel.text = "下拉刷新"
            case .Pulling:print("下拉状态")
                messageLabel.text = "释放刷新"
            case.Loading:print("加载中、。")
                messageLabel.text = "加载中"
                //加载的时候,让视图显示在 Nav下边 修改  scrollView?.contentInset
                var inset = scrollView?.contentInset
                
                inset?.top += 64
                
                scrollView?.contentInset = inset!
                
                // 没有触发 ValueChange的事件
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
                
                //记录加载的状态
                oldStatus = .Loading
            
            }
        
        }
    
    }
    
    
    func endRefreshing(){
    
        //加载完成，让状态回复到正常状态
        status = .Normal
        
        //如果当前状态为加载状态
        if oldStatus == .Loading{
        
            //加载的时候,让视图显示在 Nav下边 修改  scrollView?.contentInset
            var inset = scrollView?.contentInset
            
            inset?.top -= 64
            
            scrollView?.contentInset = inset!
            
            //恢复标记
            oldStatus = .Normal
        }
    }
    
    //自定义视图三部曲
    override  init(frame: CGRect) {
        super.init(frame:frame)
        
        //设置背景色
        backgroundColor = UIColor.yellowColor()
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //私有方法
    private func setupUI(){
    
        //设置frmae
        //获取系统的frame
        var frame = self.frame
        //修改frame
        frame.size = CGSizeMake(UIScreen.mainScreen().bounds.width, 50)
        frame.origin.y = -50
        
        //赋值
        self.frame = frame
        
        //添加控件
        addSubview(messageLabel)
        addSubview(arrowImageView)
        addSubview(loadingImageView)
        
        //添加约束
        // 水平居中,往右30个点,垂直居中
        messageLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(self.snp_centerY)
            make.centerX.equalTo(self.snp_centerX).offset(30)
        }
        // messageLabel的左边, 水平居中
        arrowImageView.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(self.snp_centerY)
            make.right.equalTo(messageLabel.snp_left)
        }
        loadingImageView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowImageView.snp_center)
        }
       
    }
    
    // 添加KVO
    // 这个方法是,我们把 子控件添加到父控件的时候会调用这个方法
    // newSuperview是 UITableView
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        // 1.先把 newSuperview 转换一下 UIScrollView
        scrollView = newSuperview as?UIScrollView
        
        //添加监听
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        
        
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let scrollView = object as? UIScrollView
        
        // 给 scrollView一个强制 ,建议大家不用强转
        if scrollView!.dragging{//拖拽的时候再去判断状态
            
            if scrollView?.contentOffset.y < -150{
            
            //改变状态(释放刷新)
                status = .Pulling
            
            }else if scrollView?.contentOffset.y < -114 && scrollView?.contentOffset.y > -150{
                
                //改变为正常状态
                status = .Normal
            }

        }else{
            
            //松手的时候去加载数据
            if scrollView?.contentOffset.y < -150 && status == .Pulling{
                status = .Loading
                
                //加载数据
            }
        
        
        }
    }
   //懒加载
    //提示语
    private lazy var  messageLabel: UILabel = {
    
        let label = UILabel()
        
        label.text = "下拉刷新"
        label.textColor = UIColor.redColor()
        label.font = UIFont.systemFontOfSize(15)
        return label
        
    }()
    //箭头
    private lazy var arrowImageView: UIImageView = {
    
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    
    //加载的视图
    private lazy var loadingImageView: UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_loading")
        
        return img
    }()
    
    //移除监听
    deinit{
    
        removeObserver(self, forKeyPath: "contentOffset")
    }
}
